package cn.geminis.crypto.cert.service.service;

import cn.geminis.crypto.cert.service.model.KeyPairRequest;
import cn.geminis.crypto.cert.service.model.KmcKeyPair;
import cn.geminis.crypto.csp.AbstractCspFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author puddi
 */
@Service
public class KmcServiceImpl implements KmcService {

    @Autowired
    private AbstractCspFactory cspFactory;

    @Override
    public KmcKeyPair requestKeyPair(KeyPairRequest request) {
        try (var keypairGenerator = this.cspFactory.createKeyPairGenerator();
             var envelope = this.cspFactory.createEnvelope()) {
            var keypair = keypairGenerator.generateKeyPair();
            var result = new KmcKeyPair();
            result.setPublicKey(keypair.getPublicKey());

            var encryptedKey = envelope.encrypt(
                    keypair.getPrivateKey().getEncoded(),
                    request.getProtectCert().getEncode());

            result.setPrivateKey(encryptedKey);
            return result;
        } catch (IOException e) {
            throw new RuntimeException("产生密钥错误", e);
        }
    }
}
